// registerdialog.cpp
#include "registerdialog.h"
#include "ui_register.h"
#include "client_network.h"
#include <QPainter>
#include <QGraphicsDropShadowEffect>
#include <QMessageBox>
#include <QRegularExpression>
#include <QMouseEvent>
#include <QTimer>

RegisterDialog::RegisterDialog(ClientNetwork *clientNet,QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::RegisterDialog)
    , m_clientNetwork(clientNet)
{
    ui->setupUi(this);

    // 设置窗口无边框和透明背景
    setWindowFlags(Qt::FramelessWindowHint);
    setAttribute(Qt::WA_TranslucentBackground);

    // 设置阴影效果
    QGraphicsDropShadowEffect *shadow = new QGraphicsDropShadowEffect(this);
    shadow->setBlurRadius(20);
    shadow->setColor(QColor(0, 0, 0, 160));
    shadow->setOffset(0, 0);
    ui->mainWidget->setGraphicsEffect(shadow);

    // 设置圆角
    ui->mainWidget->setStyleSheet("QWidget#mainWidget{background: white; border-radius: 10px;}");

    // 设置输入框样式
    QString lineEditStyle = "QLineEdit {"
                            "border: 2px solid #e0e0e0;"
                            "border-radius: 5px;"
                            "padding: 8px;"
                            "font-size: 14px;"
                            "}"
                            "QLineEdit:focus {"
                            "border-color: #4a90e2;"
                            "}";

    ui->usernameEdit->setStyleSheet(lineEditStyle);
    ui->passwordEdit->setStyleSheet(lineEditStyle);
    ui->confirmPasswordEdit->setStyleSheet(lineEditStyle);
    ui->passwordEdit->setEchoMode(QLineEdit::Password);
    ui->confirmPasswordEdit->setEchoMode(QLineEdit::Password);

    // 设置按钮样式
    QString buttonStyle = "QPushButton {"
                          "background-color: #4a90e2;"
                          "color: white;"
                          "border: none;"
                          "border-radius: 5px;"
                          "padding: 10px;"
                          "font-weight: bold;"
                          "}"
                          "QPushButton:hover {"
                          "background-color: #3a7bc8;"
                          "}"
                          "QPushButton:pressed {"
                          "background-color: #2a6bb4;"
                          "}";

    ui->registerButton->setStyleSheet(buttonStyle);
    ui->backButton->setStyleSheet(buttonStyle.replace("#4a90e2", "#50c9ba"));

    // 连接信号槽
    connect(ui->registerButton, &QPushButton::clicked, this, &RegisterDialog::onRegisterClicked);
    connect(ui->backButton, &QPushButton::clicked, this, &RegisterDialog::onBackToLoginClicked);
    connect(ui->closeButton, &QPushButton::clicked, this, &QDialog::reject);

    setFocusPolicy(Qt::StrongFocus);  // 确保对话框能接收键盘事件
    ui->usernameEdit->setFocus();     // 初始焦点放在输入框

    if(m_clientNetwork){
        connect(m_clientNetwork, &ClientNetwork::registerResponseReceived,
                this, &RegisterDialog::handleRegisterResponse);
    }
}

RegisterDialog::~RegisterDialog()
{
    delete ui;
}

QString RegisterDialog::username() const
{
    return ui->usernameEdit->text();
}

QString RegisterDialog::password() const
{
    return ui->passwordEdit->text();
}

QString RegisterDialog::confirmPassword() const
{
    return ui->confirmPasswordEdit->text();
}

bool RegisterDialog::validatePhoneNumber(const QString &phone)
{
    QRegularExpression regex("^1[3-9]\\d{9}$"); // 简单的中国大陆手机号验证
    return regex.match(phone).hasMatch();
}

void RegisterDialog::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton) {
        m_dragPosition = event->globalPos() - frameGeometry().topLeft();
        event->accept();
    }
}

void RegisterDialog::mouseMoveEvent(QMouseEvent *event)
{
    if (event->buttons() & Qt::LeftButton) {
        move(event->globalPos() - m_dragPosition);
        event->accept();
    }
}

void RegisterDialog::keyPressEvent(QKeyEvent *event) {
    if (event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter) {
        onRegisterClicked();  // 调用注册逻辑
        event->accept();
    } else {
        QDialog::keyPressEvent(event);  // 其他按键交给父类处理
    }
}

void RegisterDialog::paintEvent(QPaintEvent *event)
{
    // Q_UNUSED(event);

    // QPainter painter(this);
    // painter.setRenderHint(QPainter::Antialiasing);

    // // 绘制渐变色背景
    // QLinearGradient gradient(0, 0, width(), height());
    // gradient.setColorAt(0, QColor(100, 181, 246));
    // gradient.setColorAt(1, QColor(66, 165, 245));
    // painter.fillRect(rect(), gradient);
}

void RegisterDialog::onRegisterClicked()
{
    animateButton(ui->registerButton);

    // 验证输入
    if (username().isEmpty()) {
        ui->errorLabel->setText("用户名不能为空");
        ui->errorLabel->setStyleSheet("color: red;");
        return;
    }

    if (password().isEmpty()) {
        ui->errorLabel->setText("密码不能为空");
        ui->errorLabel->setStyleSheet("color: red;");
        return;
    }

    if (password() != confirmPassword()) {
        ui->errorLabel->setText("两次输入的密码不一致");
        ui->errorLabel->setStyleSheet("color: red;");
        return;
    }
    // 所有验证通过
    // 所有验证通过，发送注册请求
    ui->errorLabel->setText("正在注册...");
    ui->errorLabel->setStyleSheet("color: blue;");
    ui->registerButton->setEnabled(false);

    // 构造注册数据
    QJsonObject data;
    data["username"] = username();
    data["password"] = password();

    // 发送注册请求
    QByteArray request = MessageUtil::serialize(REGISTER_REQUEST, data);
    m_clientNetwork->sendMessage(request);
}

void RegisterDialog::handleRegisterResponse(const QJsonObject &response) {
    bool success = response["success"].toBool();
    QString message = response["message"].toString();

    // 重新启用注册按钮
    ui->registerButton->setEnabled(true);

    if (success) {
        QString username = response["username"].toString();

        // 使用消息框显示成功信息
        QMessageBox::information(this, "注册成功",QString("用户 %1 注册成功！").arg(username));

        QTimer::singleShot(500, this, [this]() {
            emit registerSuccess();
            accept();  // 关闭对话框
        });
    } else {
        // 使用消息框显示错误信息
        QString errorMsg = message.isEmpty() ? "注册失败" : message;
        QMessageBox::warning(this, "注册失败", errorMsg);

        // 高亮显示错误字段
        if(message.contains("username")) {
            ui->usernameEdit->setFocus();
            ui->usernameEdit->selectAll();
        }
        else if(message.contains("password")) {
            ui->passwordEdit->setFocus();
            ui->passwordEdit->selectAll();
        }
    }
}

void RegisterDialog::onBackToLoginClicked()
{
    animateButton(ui->backButton);
    emit backToLoginRequested(); // 发射返回信号
}

void RegisterDialog::animateButton(QWidget *button)
{
    QPropertyAnimation *animation = createButtonAnimation(button);
    animation->start(QPropertyAnimation::DeleteWhenStopped);
}

QPropertyAnimation *RegisterDialog::createButtonAnimation(QWidget *target)
{
    QPropertyAnimation *animation = new QPropertyAnimation(target, "geometry");
    animation->setDuration(100);
    animation->setKeyValueAt(0, target->geometry());
    animation->setKeyValueAt(0.5, target->geometry().adjusted(-5, -5, 5, 5));
    animation->setKeyValueAt(1, target->geometry());
    return animation;
}
